package com.smh.demo1.a14;

import org.aopalliance.aop.Advice;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectInstanceFactory;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice;
import org.springframework.aop.aspectj.SingletonAspectInstanceFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @author shiminghui
 * @date 2025/4/18 10:30
 * @description: TODO
 */
public class A14_2Application {
    //高级切面转低级切面
    public static void main(String[] args) {
        Method[] methods =
                MyAspect.class.getMethods();

        AspectInstanceFactory aspectInstanceFactory = new SingletonAspectInstanceFactory(new MyAspect());

        ArrayList<Advisor> advisors = new ArrayList<>();

        for (Method method : methods) {
            if (method.isAnnotationPresent(Before.class)) {
                // 获取注解里面的value值
                String value = method.getAnnotation(Before.class).value();
                // 创建切点
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(value);
                // 创建通知
                Advice advice = new AspectJMethodBeforeAdvice(method, pointcut, aspectInstanceFactory);

                // 创建切面
                DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                advisors.add(advisor);
            }
        }

        for (Advisor advisor : advisors) {
            System.out.println(advisor);
        }

    }

    @Aspect
    static class MyAspect {
        @Before("execution(* read(..))")
        public void before() {
            System.out.println("before");
        }

        @Before("execution(* read(..))")
        public void after() {
            System.out.println("after");
        }
    }
}
